package jxtcpserver

import (
	"bufio"
	"context"
	"errors"
	"net"
	"sync"
)

type Client struct {
	Id         string
	MachineId  uint32
	Conn       net.Conn
	onClose    func(error)
	onMessage  func(m *Message)
	writer     *bufio.Writer
	reader     *bufio.Reader
	sendLocker sync.Mutex
	EndError   error
	ctx        context.Context
	cancel     context.CancelFunc
}

func (c *Client) Run() {
	go func() {
		defer func() {
			c.Conn.Close()
			if c.onClose != nil {
				c.onClose(c.EndError)
			}
		}()
		for {
			select {
			case <-c.ctx.Done():
				return
			default:
				msg, err := ReadMessage(c.reader)
				if err != nil {
					serverlog.Error("读取客户端数据发生错误:", err.Error())
					c.EndError = err
					return
				}
				if c.onMessage != nil {
					go c.onMessage(msg)
				}
			}
		}
	}()
}
func (c *Client) SendMessage(m *Message) error {
	if !c.sendLocker.TryLock() {
		return errors.New("正在发送数据中")
	}
	defer c.sendLocker.Unlock()
	err := m.WriteMessage(c.writer)
	if err != nil {
		c.Close()
	}
	return err
}
func (c *Client) Close() {
	c.cancel()
}
